"use client";

import { useState, useEffect } from "react";
import { FiMoon, FiSun } from "react-icons/fi";

type Theme = "light" | "dark";

export function ThemeToggle() {
  const [theme, setTheme] = useState<Theme>("light");
  const [mounted, setMounted] = useState(false);

  // Initialize theme from localStorage or system preference
  useEffect(() => {
    setMounted(true);
    const storedTheme = localStorage.getItem("theme") as Theme | null;
    if (storedTheme) {
      setTheme(storedTheme);
      document.documentElement.classList.toggle("dark", storedTheme === "dark");
    } else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
      setTheme("dark");
      document.documentElement.classList.add("dark");
    }
  }, []);

  const toggleTheme = () => {
    const newTheme = theme === "light" ? "dark" : "light";
    setTheme(newTheme);
    localStorage.setItem("theme", newTheme);
    document.documentElement.classList.toggle("dark", newTheme === "dark");
  };

  if (!mounted) {
    return <div className="h-10 w-10" />; // Prevents layout shift
  }

  return (
    <button
      onClick={toggleTheme}
      className="relative flex h-10 w-10 items-center justify-center overflow-hidden rounded-full transition-all duration-300 hover:bg-blue-100 dark:hover:bg-blue-900/30"
      aria-label={theme === "light" ? "Switch to dark mode" : "Switch to light mode"}
    >
      <div className="relative h-6 w-6">
        <span 
          className={`absolute inset-0 flex transform items-center justify-center transition-all duration-500 ${
            theme === "light" 
              ? "rotate-0 opacity-100" 
              : "rotate-90 opacity-0"
          }`}
        >
          <FiMoon className="h-5 w-5 text-blue-600 dark:text-blue-400" />
        </span>
        <span 
          className={`absolute inset-0 flex transform items-center justify-center transition-all duration-500 ${
            theme === "dark" 
              ? "rotate-0 opacity-100" 
              : "-rotate-90 opacity-0"
          }`}
        >
          <FiSun className="h-5 w-5 text-yellow-500 dark:text-yellow-300" />
        </span>
      </div>
    </button>
  );
} 